# -*- coding: utf-8 -*-
from django import template
from django.utils.safestring import mark_safe
from pagemagic.utils.goodtext.human import numeral_suffix
import pagemagic.utils.goodtext.typo as typograph
import pagemagic.utils.goodtext.wiki as wiki
from django.utils.feedgenerator import rfc2822_date
import re
#from pagemagic.utils.goodtext.utils import trunc_text

register = template.Library()

@register.filter
def typo(s):
    return mark_safe(typograph.process_html(s))

#@register.filter
#def trunc(s, n):
#    return trunc_text(s, n)

@register.filter
def wikiinline(s):
    return mark_safe(wiki.wikiinline(s))

@register.filter
def wikiblock(s):
    return mark_safe(wiki.wikiblock(s))

@register.filter
def render(s, vars=None):
    try:
        return mark_safe(template.Template(s).render(template.Context(vars or {})))
    except Exception, e:
        return mark_safe('<!-- ERROR: %s --> %s' % (e, s))

@register.filter
def numeral(s, low_mid_hi):
    try:
        low, mid, hi = low_mid_hi.split('|')
    except ValueError:
        try:
            low, mid, hi = low_mid_hi.split(',')
        except ValueError:
            raise ValueError('`numeral` filter second parameter must have "s|s|s" format')
    try:
        num = int(s)
    except ValueError:
        return s
    if '%d' in low and '%d' in mid and '%d' in hi:
        return mark_safe(numeral_suffix(num, low, mid, hi) % num)
    else:
        return mark_safe("%d&nbsp;%s" % (num, numeral_suffix(num, low, mid, hi)))

#remove_newlines = re.compile('<(td|tr|table|ol|ul|li)>\s+<', re.UNICODE|re.IGNORECASE|re.DOTALL).sub



def drop_whitespaces(s,
    intag_re=re.compile(
        '(?P<open><'
            '(?P<tagname>td|tr|table|ol|ul|li)'
            '(?P<attrs>[^>]*)'
        '>)'
            '\s*'
            '(?P<content>.*?)'
            '\s*'
        '(?P<close></'
            '(?P=tagname)'
        '>)',
        re.UNICODE|re.IGNORECASE|re.DOTALL
    ),
    intertag_re=re.compile(
        '(?P<tag1><'
            '(?:'
                '/%(tagnames)s'
                '|'
                '%(tagnames)s(?:[^>]*)'
            ')'
        '>)'
            '\s+'
        '(?P<rest>)' % {
            'tagnames': '(?:td|li|table|ol|ul|p)'
        },
        re.UNICODE|re.IGNORECASE|re.DOTALL
    )
):
    def repl(m):
        d = m.groupdict()
        d['content'] = '%s' % drop_whitespaces(d['content'])
        return '%(open)s%(content)s%(close)s' % d
    s = intag_re.sub(repl, s)
    s = intertag_re.sub(lambda m: '%(tag1)s%(rest)s' % m.groupdict(), s)
    return s

@register.filter
def autoformat(s):
    s = s.replace('\r', '')
    s = drop_whitespaces(s)
    s = s.replace('\n', '<br />\n')
    return mark_safe(s)

@register.simple_tag
def maybe_autoformat(text, preform_autoformat):
    if preform_autoformat:
        return autoformat(text)
    else:
        return text

register.filter(rfc2822_date)
